<?php
namespace Models;

require_once('Base.php');

class FileUpload 
{
	private $_maxFileSize;
	private $_directory;
	private $_thumbDirectory;
	private $_fileTypes;
	private $_extensions;
	private $_path;
	private $_file;
	
	function __construct($path = "", $maxFileSize = 1000000, $file = "file")
	{
		$this->_path = $path;
		$this->_thumbPath = $path . "thumbs/";
		$this->_file = $file;
		
		$this->_directory = ABSPATH."/".$path;
		$this->_thumbDirectory = $this->_directory . "thumbs/";
		$this->_maxFileSize = $maxFileSize;
		$this->_fileTypes = array("image/jpeg", "image/png", "image/pjpeg");
		$this->_extensions = array("jpg", "jpeg", "png");
	}
	
	/**
	 * Kontrollerar om det är en giltig bild
	 * @return bool
	 */
	public function isValidImage($filesArray)
	{
		$extension = strtolower(substr(strrchr($filesArray[$this->_file]["name"], '.'), 1));
		
		// Kollar så att filtypen stöds, filen har rätt ändelse och inte är för stor
		if(
		in_array($filesArray[$this->_file]["type"], $this->_fileTypes) && 
		$filesArray[$this->_file]["size"] < $this->_maxFileSize &&
		in_array($extension, $this->_extensions)
		)
			return true;
		else
			return false;
	}
	
	/**
	 * @return string
	 */
	public function getExtension($src)
	{
		return strtolower(substr(strrchr($src, '.'), 1));
	}
	
	/**
	 * Laddar upp en fil
	 * @param $filesArray $_FILES-array
	 * @return bool
	 */
	public function uploadFile($filesArray)
	{
		if ($filesArray[$this->_file]["error"] > 0)
			return false;
			//echo "Return Code: " . $filesArray[$this->_file]["error"] . "<br />";
	  	else
	    {
	    	$pattern = "/[\w-]/";
			$replace = "/[^\W]/i";
			
	    	$fileName = $filesArray[$this->_file]["name"];
			$pathInfo = pathinfo($fileName);
			
			$fileName = preg_replace("/[^\w-]/i", '', $pathInfo['filename']);
			
			if(strlen($fileName)==0)
				$fileName = "x";
			
			$fileName .= ".".$pathInfo['extension'];
	    	
			$counter=2;
			
			while(file_exists($this->_directory . $fileName))
			{
				$pathInfo = pathinfo($fileName);
								
				// Om en dublett tidigare har laddats upp
				if($counter>2)
				{
					$fileName = substr($pathInfo['filename'], 0, -2);
					$fileName .= "_".$counter.".".$pathInfo['extension'];
				}
				else
					$fileName = $pathInfo['filename']."_".$counter.".".$pathInfo['extension'];
				
				$counter++; 
			}
			
  			// Om inte katalogen finns
  			if (!file_exists($this->_directory))
			    mkdir($this->_directory, 0777, true);
			
			$filePath = $this->_directory . $fileName;
			$this->_path .= $fileName;
			
			if(move_uploaded_file($filesArray[$this->_file]["tmp_name"], $filePath))
				return $this->_path;
			else
				return false;
	    }
	}
	
	/**
	 * Skapar en tumnagel av en bild
	 * @param $src string - url till källbild
	 * @param $dest string
	 * @param $width int - önskad storlek
	 * @return bool | string - false om misslyckad, url till skapad tumnagel om lyckad 
	 */
	public function createThumb($src, $width)
	{
		// Källfilens storlekar
		$extension = $this->getExtension($src);
		
		switch ($extension)
		{
			case 'png': $srcImg = @imagecreatefrompng($src); break;
			case 'jpg': $srcImg = @imagecreatefromjpeg($src); break;
			case 'jpeg': $srcImg = @imagecreatefromjpeg($src); break;
			
			default: return false;
		}
		
		$srcWidth = imagesx($srcImg);
		$srcHeight = imagesy($srcImg);
		  
		// Beräkna höjden gentemot önskad bredd
		$height = floor($srcHeight * ($width / $srcWidth));
		
		// Skapa tumnagel
		$thumb = imagecreatetruecolor($width, $height);
		
		// Tillåt transparens i png-bilder
		if($extension == 'png')
		{
			imagealphablending($thumb, false);
			imagesavealpha($thumb,true);
		}
		 
		// Kopiera källfilen i ny storlek
		if(!imagecopyresampled($thumb, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight))
			return false;

		// Om inte katalogen finns
		if(!file_exists($this->_thumbDirectory))
		    mkdir($this->_thumbDirectory, 0777, true);
		
		// Skapa tumnagel
		$srcFileName = basename($src);
		$thumbPath = $this->_thumbDirectory . $srcFileName;
		
		// Lagra relativ sökväg i DB 
		$this->_thumbPath .= $srcFileName; 
		
		// Sparar filen i rätt format
		switch ($extension)
		{
			case 'png':
				if(!imagepng($thumb, $thumbPath))
					return false;
				break;
				
			case 'jpg':
				if(!imagejpeg($thumb, $thumbPath))
					return false;
				break;
			
			case 'jpeg':
				if(!imagejpeg($thumb, $thumbPath))
					return false;
				break;
				
			default:
				return false;
		}
		 
		//return $thumbPath;
		return $this->_thumbPath;
	}
}
?>